import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {InformationDto} from './dto/information.dto'
import { Information} from './entities/information.entity'
@Injectable()
export class InformationService {
  constructor(
    @InjectModel('Informations') private readonly informationModel:Model<Information>
) {}
  async create(informationDto: InformationDto) {
    return await this.informationModel.insertMany(informationDto);
  }

  async findAll():Promise<InformationDto[]> {
    return await this.informationModel.find().exec();
  }

  async search(keyword: string, targ: string, userId: string):Promise<InformationDto[]> {
   if(keyword)  return await this.informationModel.find({keyword:{$regex:keyword}, userId: userId});
   if(targ) return await this.informationModel.find({targ:targ, userId: userId});
  }

  async update(id: string, informationDto: InformationDto) {
    return await this.informationModel.updateOne({_id:id}, informationDto);
  }

  async remove(id: string):Promise<any> {
    return await this.informationModel.deleteOne({_id:id});
  }

  async list(page: number, pageSize: number, userId: string):Promise<any> {
    const skip = (page - 1) * pageSize;
    const data = await this.informationModel.find({userId:userId}).sort({ time: -1 })
    const list = await this.informationModel.find({userId:userId}).sort({ time: -1 }).skip(skip).limit(pageSize)
    return {total: data.length, list: list}
  }

}
